package com.icesoft.core.dao.base;

import com.icesoft.core.dao.criteria.FromBuilder;
import com.icesoft.core.dao.criteria.SelectBuilder;
import com.icesoft.core.dao.suppose.HqlQuerySuppose;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;

@Service
@Slf4j
class DaoFacade extends EntityManagerDao {

    DaoFacade(HqlQuerySuppose hqlQuerySuppose) {
        super(hqlQuerySuppose);
    }

    public boolean isExist(FromBuilder fromBuilder) {
        return findSingle(SelectBuilder.isExist().builder(fromBuilder.offsetLimit(0, 1))) != null;
    }

    public int count(FromBuilder fromBuilder) {
        SelectBuilder selectBuilder = SelectBuilder.count().builder(fromBuilder);
        return ((Long) findSingle(selectBuilder)).intValue();
    }

    @Transactional
    public <T extends Model> void batchCreate(Collection<T> models) {
        int size = models.size();
        int i = 0;
        for (T model : models) {
            create(model);
            ++i;
            if (i % 1000 == 0 || i == size) {
                getEntityManager().flush();
                getEntityManager().clear();
            }
        }
    }

    @Transactional
    public <T extends Model> void batchUpdate(Collection<T> models) {
        int size = models.size();
        int i = 0;
        for (T model : models) {
            update(model);
            ++i;
            if (i % 1000 == 0 || i == size) {
                getEntityManager().flush();
                getEntityManager().clear();
            }
        }
    }

    @Transactional
    public <T extends Model> void batchDelete(Collection<T> models) {
        int size = models.size();
        int i = 0;
        for (T model : models) {
            delete(model);
            ++i;
            if (i % 1000 == 0 || i == size) {
                getEntityManager().flush();
                getEntityManager().clear();
            }
        }
    }

}
